package com.bolt.support.spring.jpa.ext;

import org.hibernate.QueryException;
import org.hibernate.dialect.MySQL5Dialect;
import org.hibernate.dialect.function.SQLFunction;
import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.engine.spi.Mapping;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.type.StandardBasicTypes;
import org.hibernate.type.Type;

import java.util.List;

/**
 * Created by Administrator on 2021/1/20.
 */
public class ExtMySQLDialect extends MySQL5Dialect {

    public ExtMySQLDialect() {
        super();
        registerFunction("group_concat", new GroupConcatFunction(false));

        registerFunction("group_concat_distinct", new GroupConcatFunction(true));

        registerFunction( "instr", new StandardSQLFunction("instr", StandardBasicTypes.INTEGER) );

    }


    class GroupConcatFunction  implements SQLFunction {

        boolean isDistinct = false;

        public GroupConcatFunction(boolean isDistinct) {
            this.isDistinct = isDistinct;
        }

        @Override
        public boolean hasArguments() {
            return true;
        }

        @Override
        public boolean hasParenthesesIfNoArguments() {
            return true;
        }

        @Override
        public Type getReturnType(Type firstArgumentType, Mapping mapping)
                throws QueryException {
            return StandardBasicTypes.STRING;
        }

        @Override
        public String render(Type firstArgumentType, List arguments,
                             SessionFactoryImplementor factory) throws QueryException {
            if (arguments.size() != 1) {
                throw new QueryException(new IllegalArgumentException(
                        "group_concat shoudl have one arg"));
            }
            return isDistinct ? "group_concat( DISTINCT " + arguments.get(0) + ")" : "group_concat( " + arguments.get(0) + ")";
        }
    }

    }

 